#!/bin/sh
#============================================================
#   🛰️  WAN/WAN6 接口智能切换工具 (Kwrt / OpenWrt)
#------------------------------------------------------------
#   功能:
#     • 自动检测系统以太网接口 (eth*)
#     • 显示当前 WAN / WAN6 接口绑定
#     • 检测接口链路状态 (UP/DOWN)
#     • 安全切换 network.wan.device / wan6.device
#     • 自动保存并重启网络服务
#------------------------------------------------------------
#   作者: Jun Wan + ChatGPT
#   版本: v1.2 (2025-10)
#============================================================

banner() {
cat << "EOF"

============================================================
           🛰️  WAN/WAN6 接口智能切换工具（Kwrt/OpenWrt）
------------------------------------------------------------
 当前功能:
   • 自动检测接口状态 (UP/DOWN)
   • 一键切换 WAN / WAN6 的物理设备绑定
   • 安全检查防止无效接口导致断网
------------------------------------------------------------
 作者: Jun Wan + ChatGPT
============================================================

EOF
}

banner

# 获取当前接口
CUR_WAN=$(uci get network.wan.device 2>/dev/null)
CUR_WAN6=$(uci get network.wan6.device 2>/dev/null)

echo "当前 WAN  接口:  ${CUR_WAN:-未配置}"
echo "当前 WAN6 接口:  ${CUR_WAN6:-未配置}"
echo "------------------------------------------------------------"

# 检测系统中存在的以太网接口
ALL_IFACES=$(ip -o link show | awk -F': ' '{print $2}' | grep '^eth')
echo "系统检测到的以太网接口:"
for iface in $ALL_IFACES; do
    LINK_STATE=$(ip link show "$iface" | grep -q "state UP" && echo "UP" || echo "DOWN")
    echo "  • $iface  ($LINK_STATE)"
done

echo "------------------------------------------------------------"
echo "请选择要切换到的接口:"

i=1
for iface in $ALL_IFACES; do
    echo "  $i) $iface"
    eval opt$i=$iface
    i=$((i+1))
done

echo "  q) 退出"
echo "------------------------------------------------------------"
read -p "请输入选项编号 [1-$(($i-1))/q]: " choice

if [ "$choice" = "q" ] || [ "$choice" = "Q" ]; then
    echo "已退出."
    exit 0
fi

# 选择接口
eval NEW_IF=\$opt$choice
if [ -z "$NEW_IF" ]; then
    echo "❌ 无效选项，退出。"
    exit 1
fi

# 检查接口存在
if ! ip link show "$NEW_IF" >/dev/null 2>&1; then
    echo "❌ 接口 $NEW_IF 不存在，退出。"
    exit 1
fi

# 检测接口是否 UP
LINK_STATE=$(ip link show "$NEW_IF" | grep -q "state UP" && echo "UP" || echo "DOWN")
if [ "$LINK_STATE" = "DOWN" ]; then
    echo "⚠️  警告: 接口 $NEW_IF 当前为 DOWN 状态，可能没有物理连接。"
    read -p "是否仍要切换？(y/N): " confirm
    [ "$confirm" != "y" ] && echo "已取消操作。" && exit 0
fi

# 执行切换
echo "🔄 正在切换 WAN/WAN6 到 $NEW_IF ..."
uci set network.wan.device="$NEW_IF"
uci set network.wan6.device="$NEW_IF"
uci commit network

echo "🚀 正在重启网络服务..."
/etc/init.d/network restart >/dev/null 2>&1 && echo "✅ 切换完成！" || echo "⚠️ 网络重启失败，请手动检查。"

echo "------------------------------------------------------------"
echo "当前 WAN  接口: $(uci get network.wan.device)"
echo "当前 WAN6 接口: $(uci get network.wan6.device)"
echo "============================================================"
